<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import { useHotWordAddOrUpdate, useHotWordShow } from '@fl/api/advertising-api/page-config'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'

const props = defineProps<{
    activeTreeId?: number | string,
}>()
const { activeTreeId } = toRefs(props)
const visible = defineModel<boolean>('visible', { required: true })
const id = defineModel<string>('id', { required: true })


const formRef = ref()
const title = ref<string>('添加热词')

const initialState = {
    hotWord: '',
    remark: '',
}
const state = ref(cloneDeep(initialState))

// 详情
const { data: detail, isLoading } = useHotWordShow(id)
watchEffect(() => {
    if (detail.value) {
        title.value = '编辑热词'
        state.value = cloneDeep(detail.value)
    }
})

// 提交表单
const { isPending, mutate } = useHotWordAddOrUpdate()

// 提交
async function submit() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const params = {
            id: id.value ?? '',
            pageResourceId: activeTreeId.value,
            ...unref(state),
        }
        console.log('params', params)
        mutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                cancel()
            },
        })
    }
}

function cancel() {
    visible.value = false
}

function reset() {
    id.value = ''
    formRef.value.formInstance.resetFields()
}

const columns: PlusColumn[] = [
    {
        label: '热词',
        fieldProps: {
            maxlength: 20,
        },
        prop: 'hotWord',
    },
    {
        label: '备注',
        prop: 'remark',
    },
]

const rules = {
    hotWord: [
        {
            message: '请输入热词',
            required: true,
        },
    ],
}
</script>

<template>
    <PlusDialog v-model="visible" :title="title" width="500" close-on-press-escape :has-footer="false" @cancel="cancel"
        @closed="reset">
        <ElSkeleton v-if="isLoading" animated class="mt-20" />

        <template v-else>
            <div class="mt-20 plusform">
                <PlusForm ref="formRef" v-model="state" :columns="columns" :label-width="120" :rules="rules"
                    :has-footer="false" :row-props="{ gutter: 20 }">
                </plusform>
            </div>

            <div class="mx-auto mt20 flex justify-center">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary" :loading="isPending" @click="submit">
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
